<?php

namespace App\Helpers;

/**
 * Class Common Helper
 */
class Common
{

    /**
     * 树状 select
     */
    public static function makeTreeOptions($model, $where = [], $orderBy = [], $defaultOptions = [], $id = 0, $titleField = 'title', $parentField = 'parent_id')
    {
        $options = [];
        if (!empty($defaultOptions)) {
            $options = $defaultOptions;
        }
        $recursive = function ($id, $level) use (&$recursive, $model, $where, $orderBy, &$options, $titleField, $parentField) {
            $space = '';
            for ($i = 0; $i < $level; $i++) {
                $space .= '&nbsp;&nbsp;';
            }
            if ($level) {
                $space .= '&nbsp;├&nbsp;';
            }

            $model = $model::where(array_merge([$parentField => $id], $where));
            if (!empty($orderBy)) {
                foreach ($orderBy as $key => $val) {
                    $model = $model->orderBy($key, $val);
                }
            }

            $results = $model->get();
            foreach ($results as $result) {
                $options[$result->id] = $result->id . '. ' . $space . $result->{$titleField};
                $recursive($result->id, $level + 1);
            }
        };
        $recursive($id, 0);

        return $options;
    }

    /**
     * 树状列表 (包含所有字段)
     */
    public static function getTreeList($model, $where = [], $orderBy = [], $id = 0, $titleField = 'title', $parentField = 'parent_id', $useSpace = false)
    {
        $options = [];
        $recursive = function ($id, $level) use (&$recursive, $model, $where, $orderBy, &$options, $titleField, $parentField, $useSpace) {
            $newModel = $model::where(array_merge([$parentField => $id], $where));
            if (!empty($orderBy)) {
                foreach ($orderBy as $key => $val) {
                    $newModel = $newModel->orderBy($key, $val);
                }
            }

            $results = $newModel->get();
            foreach ($results as $result) {
                if ($useSpace) {
                    $space = '';
                    for ($i = 1; $i < $level; $i++) {
                        //$space .= '&nbsp;&nbsp;';
                        $space .= '&nbsp;│&nbsp;';
                    }
                    if ($level > 1) {
                        $space .= '&nbsp;├─&nbsp;';
                    }
                    $result->$titleField = $space . $result->$titleField;
                }

                if ($model::where(array_merge([$parentField => $result->id], $where))->count()) {
                    $result->has_children = 1;
                }
                $result->level = $level;
                $options[$result->id] = $result;
                $recursive($result->id, $level + 1);
            }
        };

        $recursive($id, 1);

        return $options;
    }

    /**
     * 后台管理员操作记录
     */
    public static function adminLog($request, $logInfo)
    {
        $data['admin_id'] = $data['created_id'] = $request->user('admin')->id;
        $data['info'] = $logInfo;
        $data['ip'] = get_IP();
        $data['url'] = $request->route()->getActionName();
        $data['created_at'] = time();

        $model = new \App\Models\AdminLog;
        $model->create($data);
    }

    /**
     * CURL请求
     *
     * @param string $url 请求url地址
     * @param string $method 请求方法 get post
     * @param null $params 参数
     * @param array $headers 请求header信息
     * @param bool|false $debug 调试开启 默认false
     * @return mixed
     */
    public static function curlRequest($url, $method, $params = null, $headers = [], $debug = false)
    {
        $method = strtoupper($method);
        $ci = curl_init();
        // Curl settings
        curl_setopt($ci, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
        //curl_setopt($ci, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); // 模拟用户使用的浏览器
        curl_setopt($ci, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 6.2; WOW64; rv:34.0) Gecko/20100101 Firefox/34.0");
        curl_setopt($ci, CURLOPT_CONNECTTIMEOUT, 60); // 在发起连接前等待的时间，如果设置为0，则无限等待
        curl_setopt($ci, CURLOPT_TIMEOUT, 7); // 设置cURL允许执行的最长秒数
        curl_setopt($ci, CURLOPT_RETURNTRANSFER, true);  // 获取的信息以文件流的形式返回

        switch ($method) {
            case 'POST':
                curl_setopt($ci, CURLOPT_POST, true); // 发送一个常规的Post请求
                if (!empty($params)) {
                    $tmpDataStr = is_array($params) ? http_build_query($params) : $params;
                    curl_setopt($ci, CURLOPT_POSTFIELDS, $tmpDataStr); // Post提交的数据包
                }
                break;
            default:
                curl_setopt($ci, CURLOPT_CUSTOMREQUEST, $method); // 设置请求方式
                break;
        }
        $ssl = preg_match('/^https:\/\//i', $url) ? TRUE : FALSE;
        curl_setopt($ci, CURLOPT_URL, $url); // 要访问的地址
        curl_setopt($ci, CURLOPT_HEADER, 0); // 显示返回的Header区域内容
        if ($ssl) {
            curl_setopt($ci, CURLOPT_SSL_VERIFYPEER, FALSE); // https请求 不验证证书和hosts
            curl_setopt($ci, CURLOPT_SSL_VERIFYHOST, FALSE); // 不从证书中检查SSL加密算法是否存在
        }
        //curl_setopt($ci, CURLOPT_HEADER, true); // 启用时会将头文件的信息作为数据流输出
        curl_setopt($ci, CURLOPT_FOLLOWLOCATION, 1); // 使用自动跳转
        curl_setopt($ci, CURLOPT_MAXREDIRS, 2); // 指定最多的HTTP重定向的数量，这个选项是和CURLOPT_FOLLOWLOCATION一起使用的
        curl_setopt($ci, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ci, CURLINFO_HEADER_OUT, true);
        //curl_setopt($ci, CURLOPT_COOKIE, $cookieStr); // COOKIE带过去

        $response = curl_exec($ci);
        $requestInfo = curl_getinfo($ci);
        //$httpCode = curl_getinfo($ci, CURLINFO_HTTP_CODE);
        if ($debug) {
            echo "=====post data======\r\n";
            var_dump($params);
            echo "=====info===== \r\n";
            print_r($requestInfo);
            echo "=====response=====\r\n";
            print_r($response);
        }
        curl_close($ci);

        return $response;
    }
}
